package com.stenio.fancat.controller.shop;

import com.baomidou.mybatisplus.plugins.Page;
import com.stenio.fancat.controller.Result;
import com.stenio.fancat.domain.shop.*;
import com.stenio.fancat.form.shop.ShopForm;
import com.stenio.fancat.mapper.shop.FcShopMapper;
import com.stenio.fancat.service.enums.RedPacketSendType;
import com.stenio.fancat.service.shop.*;
import com.stenio.fancat.util.RedisUtil;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zhangqiu
 * @date 2018/12/1
 * @desc
 **/
@RestController
@RequestMapping("shop")
public class ShopController {
    @Autowired
    private ShopService shopService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private VenderService venderService;

    @Autowired
    private VenderImageService venderImageService;

    @Autowired
    private ShopImageService shopImageService;

    @Autowired
    private FcShopMapper fcShopMapper;

    @Autowired
    private RedisUtil redisUtil;

    @PostMapping("add")
    @ResponseBody
    public Result<FcShop> add(@RequestBody ShopForm shopForm){
        Result<FcShop> result = new Result();
        FcShop shop = shopService.saveWare(shopForm);
        result.setData(shop);
        redisUtil.del("shopGoods"+shopForm.getCategoryId(),"category::1");
        return result;
    }

    @PostMapping("update")
    @ResponseBody
    public Result update(@RequestBody ShopForm shopForm){
        FcShop oldFcShop = fcShopMapper.selectById(shopForm.getId());
        Result<FcShop> result = new Result();
        result.setData(shopService.updateWare(shopForm));
        redisUtil.del("shopGoods"+shopForm.getCategoryId(),"shopGoods"+oldFcShop.getCategoryId(),"shopGoodsSingle"+shopForm.getId(),"category::1");
        return result;
    }

    @GetMapping("get/{id}")
    @ResponseBody
    public Result get(@PathVariable Integer id){
        Result<ShopVo> result = new Result();
        FcShop shop = shopService.getById(id);
        if(shop == null) {
            result.setFlag(Result.FLAG.failure);
            return result;
        }
        ShopVo shopVo = shopToVo(shop);
        redisUtil.set("shopGoodsSingle"+id,shopVo);
        result.setData(shopVo);
        return result;
    }

    @PostMapping("page")
    @ResponseBody
    public Result page(@RequestBody ShopForm shopForm){
        System.out.println(shopForm);
        Result<Map<String,Object>> result = new Result();
        Page<FcShop> page = shopService.selectByPage(shopForm);
        Map<String,Object> data = new HashMap<>();
        if(page!=null){
            data.put("current",page.getCurrent());
            data.put("pages",page.getPages());
            data.put("size",page.getSize());
            data.put("total",page.getTotal());
            List<ShopVo> records = new ArrayList<>();
            if(CollectionUtils.isNotEmpty(page.getRecords())){
                page.getRecords().stream().forEach(shop->{
                    records.add(shopToVo(shop));
                });
            }
            data.put("records",records);
        }
        result.setData(data);
        return result;
    }

    public ShopVo shopToVo(FcShop shop){
        FcCategory category2 = categoryService.findById(shop.getCategoryId());
        FcCategory category1 = categoryService.findById(category2.getParentId());
        FcShopImage f = new FcShopImage();
        f.setBusinessId(shop.getId());
        f.setType(1);
        List<FcShopImage> fcShopImage = shopImageService.selectByType(f);
        FcVender vender = venderService.findById(shop.getVenderId());
        FcVenderImage venderImage = venderImageService.findById(shop.getVenderId());
        ShopVo vo = new ShopVo();
        BeanUtils.copyProperties(shop,vo);
        vo.setCat1Name(category1.getName());
        vo.setCat2Name(category2.getName());
        vo.setCatLev1(category1.getId());
        vo.setVenderName(vender.getName());
        vo.setWxCode(venderImage.getWxCode());
        if(shop.getSendType() != null) {
            vo.setSendTypeName(RedPacketSendType.getEnumByStatus(shop.getSendType()).getDesc());
        }
        for(FcShopImage fc : fcShopImage) {
            vo.setImageUrl(fc.getUrl());
        }
        return vo;
    }

    @PostMapping("onOff/{id}/{status}")
    @ResponseBody
    public Result onOff(@PathVariable Integer id, @PathVariable Integer status){
        FcShop fcShop = shopService.getById(id);
        Result<FcShop> result = new Result();
        try {
            result.setData(shopService.onOff(id,status));
            redisUtil.del("shopGoods"+fcShop.getCategoryId(),"shopGoodsSingle"+id,"category::1");
        } catch (Exception e) {
            result.setFlag(Result.FLAG.failure);
            result.setMsg("上下架状态不合法");
        }
        return result;
    }

    /**
     * 修改商品热销
     * @param id
     * @param status
     * @return
     */
    @PostMapping("hotOnOff/{id}/{status}")
    @ResponseBody
    public Result hotOnOff(@PathVariable Integer id, @PathVariable Integer status){
        FcShop fcShop = shopService.getById(id);
        Result<FcShop> result = new Result();
        try {
            result.setData(shopService.hotOnOff(id,status));
            redisUtil.del("shopGoods"+fcShop.getCategoryId(),"shopGoodsSingle"+id,"category::1");
        } catch (Exception e) {
            result.setFlag(Result.FLAG.failure);
            result.setMsg("修改热销状态不合法");
        }
        return result;
    }

    /**
     * 根据二级品类id查询商品
     *      * @param id
     * @return
     */
    @PostMapping("findSecondaryId/{id}")
    @ResponseBody
    public Result findSecondaryId(@PathVariable Integer id){
        String key = "shopGoods" + id;
        Object redisData = redisUtil.get(key);
        Result<List<ShopVo>> result = new Result<>();
        if(redisData == null) {
            List<FcShop> fcShops = shopService.selectByCategoryId(id);
            List<ShopVo> shopVos = new ArrayList<>();
            if(CollectionUtils.isNotEmpty(fcShops)){
                fcShops.stream().forEach(shop->{
                    shopVos.add(shopToVo(shop));
                });
            }else {
                result.setFlag(Result.FLAG.failure);
                return result;
            }
            redisUtil.set(key,shopVos);
            result.setData(shopVos);
        }else {
            result.setData((List<ShopVo>)redisData);
        }
        return result;
    }

    @PostMapping("findHotGoodsAll")
    @ResponseBody
    public Result findHotGoodsAll() {
        Result<List<ShopVo>> result = new Result<>();
        List<FcShop> fcShops = shopService.selectHotGoodsAll();
        List<ShopVo> shopVos = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(fcShops)) {
            fcShops.stream().forEach(shop->{
                shopVos.add(shopToVo(shop));
            });
        }else {
            result.setFlag(Result.FLAG.failure);
            return result;
        }
        result.setData(shopVos);
        return result;
    }
}
